package org.com.curry.lee.utils.algorithm.algorithm;

import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SubImage {
    private  static  String SAVE_PATH = "var/pic/localPic/";
    public String getSubImage (String urlImage,int x,int y,int width,int height) throws IOException{
        //https://henghao-edu.oss-cn-qingdao.aliyuncs.com/2022/11/25/51a1b756631d487f911febde3991d7e1.png
        URL url = new URL(urlImage);
        BufferedImage bufImage = ImageIO.read(url);
        //BufferedImage subimage = bufImage.getSubimage(550, 490, 730, 450);
        BufferedImage subimage = bufImage.getSubimage(x, y, width, height);
        Date now = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String nowDate = simpleDateFormat.format(now);
        //文件保存路径后添加当前日期目录 例:/var/pic/localPic/2022/11/25
        String imagePath = SAVE_PATH+nowDate;
        //保存的文件名称 实际使用可以调用生成uuid
        //       String imageName = "CPR7fa797ec84744fae974e3ed48685812e"+".png";
        String imageName = IdUtils.randomUUID().replaceAll("-", "") + ".png";
        File ImageDir = new File(imagePath);
        if(!ImageDir.exists()){
            ImageDir.mkdirs();  //创建目录
        }
        String fileName = imagePath +"/"+ imageName;
        File imageDir = new File(fileName);
        System.out.println(imageDir.getAbsoluteFile());
        System.out.println(fileName);
        ImageIO.write(subimage, "png",imageDir );
        return imageDir.getAbsolutePath();
    }
}
